package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户列表
     * @param userVo
     * @return
     */
    @Override
    public PageInfo list(UserVo userVo) {
        if (userVo == null) {
            return new PageInfo(userMapper.selectAll());
        }
        if (userVo.getCurrentPage() != null && userVo.getPageSize() != null) {
            PageHelper.startPage(userVo.getCurrentPage(), userVo.getPageSize());
        }

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        //添加用户名查询条件
        if (userVo.getUserName() != null && !"".equals(userVo.getUserName())) {
            criteria.orLike("userName","%"+ userVo.getUserName()+"%");
        }
        //添加评论状态查询条件
        if (userVo.getCommentStatus() != null) {
            criteria.andEqualTo("commentStatus", userVo.getCommentStatus());
        }
        //查询用户标签条件
        if (userVo.getUserTag() != null) {
            criteria.andEqualTo("userTag", userVo.getUserTag());
        }
        List<User> users = userMapper.selectByExample(example);
        return new PageInfo(users);
    }

    /**
     * 修改用户信息
     * @param userVo
     */
    @Override
    @Transactional
    public void edit(UserVo userVo) {
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        int i = userMapper.updateByPrimaryKeySelective(user);
        //如果没有修改到信息就返回异常
        if (i <= 0) {
            throw new RuntimeException("没有这个用户");
        }
    }

    /**
     * 删除用户信息
     * @param userVo
     */
    @Override
    @Transactional
    public void delete(UserVo userVo) {
        User user = new User();
        BeanUtils.copyProperties(userVo, user);

        int i = userMapper.deleteByPrimaryKey(user);
        if (i == 0) {
            throw new RuntimeException("没有这个用户");
        }

    }

    /**
     * 重置密码
     * @param userVo
     */
    @Override
    public void resetpassword(UserVo userVo) {
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        //springboot自带的MD5加密工具类
        user.setPassWord(DigestUtils.md5DigestAsHex(user.getPassWord().getBytes()));
        userMapper.updateByPrimaryKeySelective(user);
    }

}
